# This files contains your custom actions which can be used to run
# custom Python code.
#
# See this guide on how to implement these action:
# https://rasa.com/docs/rasa/custom-actions


# This is a simple example for a custom action which utters "Hello World!"

from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.events import SlotSet
import requests
import os

ment2ent_file = os.listdir('D:\\大四\\RASA实践\\DBpedia_ment2ent副本')
triplet_file = os.listdir('D:\\大四\\RASA实践\\DBpedia_triplet副本')

def Weather(city, date):
    url = 'https://api.seniverse.com/v3/weather/daily.json?key=SKUsQjiqVv2wX4RDF&location={}&language=zh-Hans&unit=c&start=0&days=3'.format(city)
    json_data = requests.get(url).json()
    if 'results' in json_data:
        format_add = json_data['results'][0]['daily']
        if date == '明天':
            return format_add[1]
        elif date == '后天':
            return format_add[2]
        else:
            return format_add[0]
    return False

# class ActionHelloWorld(Action):
#
#     def name(self) -> Text:
#         return "action_hello_world"
#
#     def run(self, dispatcher: CollectingDispatcher,
#             tracker: Tracker,
#             domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
#
#         dispatcher.utter_message(text="Hello World!")
#
#         return []

class ActionWeatherAPI(Action):

    def name(self) -> Text:
        return "action_weather_api"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:

        city = tracker.get_slot("location")
        date = tracker.get_slot("which_day")
        temp = Weather(city, date)# 调用接口获取
        if not temp:
            dispatcher.utter_message(text = "没有此位置的天气信息") # 传递到response中
        else:
            dispatcher.utter_message(text = "{0}({1}){2}的天气为：白天{3}，气温{4}°C，晚上{5}，气温{6}°C。最高温度{7}°C，最低温度{8}°C。降水量{9}mm。风力{10}级。".\
                                             format(date, temp['date'], city, temp['text_day'], temp['code_day'], temp['text_night'],
                                             temp['code_night'], temp['high'], temp['low'], temp['rainfall'], temp['wind_scale'])) # 传递到response中
        return []

class ActionDBpediament2entAPI(Action):
    #访问DBpedia获取知识
    def name(self) -> Text:
        return "action_DBpedia_ment2ent_api"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        """
        #查询实体指称项名称
        DBpedia_mentname = tracker.get_slot("DBpedia_mentname")
        url = 'http://shuyantech.com/api/cndbpedia/ment2ent?q={}'.format(DBpedia_mentname)
        json_ment2ent = requests.get(url).json()['ret']
        """
        DBpedia_mentname = tracker.get_slot("DBpedia_mentname")
        json_ment2ent = []
        if '{}.txt'.format(DBpedia_mentname[0]) not in ment2ent_file:
            dispatcher.utter_message(text = "你要查询的信息不存在。")
        else:
            with open('D:\大四\RASA实践\DBpedia_ment2ent副本\\{}.txt'.format(DBpedia_mentname[0]), "r", encoding="utf-8") as f:
                for line in f:
                    strs = line[:-1].split(' || ')#把回车去掉
                    if len(strs) == 2 and strs[0] == DBpedia_mentname:
                        json_ment2ent.append(strs[1])
            #记录指称项名称数量，若只有一个，得到实体全称，若有多个，需要询问用户具体想查哪一个
            entity_num = len(json_ment2ent)
            if(entity_num == 1):
                return [SlotSet("DBpedia_entity", json_ment2ent[0])]
            elif(entity_num > 1):
                entity_info = "实体{}为多义词：\n".format(DBpedia_mentname)
                for item in json_ment2ent:
                    entity_info += item + '\n'
                dispatcher.utter_message(text = entity_info)
            else:
                dispatcher.utter_message(text = "你要查询的信息不存在。")
        return [SlotSet("DBpedia_mentname", None)]

class ActionDBpediamentAPI(Action):
    #访问DBpedia获取知识
    def name(self) -> Text:
        return "action_DBpedia_ent_api"

    def run(self, dispatcher: CollectingDispatcher, tracker: Tracker,
            domain: Dict[Text, Any]) -> List[Dict[Text, Any]]:
        #查询实体
        DBpedia_entity = tracker.get_slot("DBpedia_entity")
        DBpedia_attr = tracker.get_slot("DBpedia_attr")
        #根据是否有属性来决定api使用
        if(not DBpedia_attr):
            """
            url = 'http://shuyantech.com/api/cndbpedia/avpair?q={}'.format(DBpedia_entity)
            json_ent = requests.get(url).json()['ret']
            """
            json_ent = []
            if '{}.txt'.format(DBpedia_entity[0]) not in triplet_file:
                dispatcher.utter_message(text = "你要查询的信息不存在。")
            else:
                with open('D:\大四\RASA实践\DBpedia_triplet副本\\{}.txt'.format(DBpedia_entity[0]), "r", encoding="utf-8") as f:
                    for line in f:
                        strs = line[:-1].split(' || ')#把回车去掉
                        if len(strs) == 3 and strs[0] == DBpedia_entity:
                            json_ent.append((strs[1],strs[2]))
            entity_info_num = len(json_ent)
            if(entity_info_num != 0):
                entity_info = ""
                for item in json_ent:
                    entity_info += item[0] + ':' + item[1] + '\n'
                dispatcher.utter_message(text = entity_info)
            else:
                dispatcher.utter_message(text = "你要查询的信息不存在。")
        else:
            """
            url = 'http://shuyantech.com/api/cndbpedia/value?q={0}&attr={1}'.format(DBpedia_entity, DBpedia_attr)
            json_ent = requests.get(url).json()['ret']
            """
            json_ent = []
            if '{}.txt'.format(DBpedia_entity[0]) not in triplet_file:
                dispatcher.utter_message(text = "你要查询的信息不存在。")
            else:
                with open('D:\大四\RASA实践\DBpedia_triplet副本\\{}.txt'.format(DBpedia_entity[0]), "r", encoding="utf-8") as f:
                    for line in f:
                        strs = line[:-1].split(' || ')#把回车去掉
                        if len(strs) == 3 and strs[0] == DBpedia_entity and strs[1] == DBpedia_attr:
                            json_ent.append(strs[2])
            entity_info_num = len(json_ent)
            if(entity_info_num != 0):
                entity_info = ""
                for item in json_ent:
                    entity_info += item + ' '
                dispatcher.utter_message(text = entity_info)
            else:
                dispatcher.utter_message(text = "你要查询的信息不存在。")
        return [SlotSet("DBpedia_entity", None), SlotSet("DBpedia_attr", None)]